package com.mxfcode.back.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mxfcode.back.dto.ArticleDTO;
import com.mxfcode.back.dto.PlateDTO;
import com.mxfcode.back.mapper.BackArticleMapper;
import com.mxfcode.back.mapper.CategoryMapper;
import com.mxfcode.back.mapper.BackPlateMapper;
import com.mxfcode.back.service.BackArticleService;
import com.mxfcode.bbs_common.date.DateUtils;
import com.mxfcode.bbs_common.response.PageDataResult;
import com.mxfcode.bbs_common.util.AOSUtils;
import com.mxfcode.bbs_common.util.community.CommunityUtil;
import com.mxfcode.common.HostHolder;
import com.mxfcode.constants.ArticleConstants;
import com.mxfcode.entity.BBSArticle;
import com.mxfcode.entity.BBSCategory;
import com.mxfcode.entity.BBSPlate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @类名 PlateServiceImpl
 * @描述 博文管理业务
 * @作者 mxf
 * @创建日期 2021-03-05 14:02
 **/
@Service
public class BackArticleServiceImpl implements BackArticleService {
    private static final Logger logger = LoggerFactory.getLogger(BackArticleServiceImpl.class);

    @Resource
    private BackPlateMapper backPlateMapper;
    @Resource
    private HostHolder hostHolder;
    @Resource
    private BackArticleMapper backArticleMapper;
    @Resource
    private CategoryMapper categoryMapper;


    @Override
    public Map<String, Object> updatePlate(BBSPlate plate) throws Exception {
        Map<String,Object> data = new HashMap();
        try{
            plate.setUpdateName(hostHolder.getUser().getRealName());
            plate.setUpdateBy(hostHolder.getUser().getUserName());
            plate.setUpdateDate(DateUtils.getCurrentDateToDate());
            int result = backPlateMapper.updatePlate(plate);
            if(result == 0){
                data.put("code",0);
                data.put("msg","更新失败！");
                logger.error("博文[更新]，结果=更新失败！");
                return data;
            }
            data.put("code",1);
            data.put("msg","更新成功！");
            logger.info("博文[更新]，结果=更新成功！");
        }catch (Exception e) {
            e.printStackTrace();
            logger.error("博文[更新]异常！", e);
            return data;
        }
        return data;
    }

    @Override
    public Map<String, Object> del(String id) {
        Map<String, Object> data = new HashMap<>();
        try {
            // 删除博文
            int result = backArticleMapper.del(id);
            if(result == 0){
                data.put("code",0);
                data.put("msg","删除博文失败");
                logger.error("删除博文失败");
                return data;
            }
            data.put("code",1);
            data.put("msg","删除博文成功");
            logger.info("删除博文成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除博文异常！", e);
        }
        return data;
    }

    @Override
    public Map<String, Object> recoverPlate(String id, Integer status) {
        Map<String, Object> data = new HashMap<>();
        try {
            // 恢复博文
            int result = backPlateMapper.del(id);
            if(result == 0){
                data.put("code",0);
                data.put("msg","恢复博文失败");
                logger.error("恢复博文失败");
                return data;
            }
            data.put("code",1);
            data.put("msg","恢复博文成功");
            logger.info("恢复博文成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("恢复博文异常！", e);
        }
        return data;
    }

    @Override
    public PageDataResult getPlateList(Integer pageNum, Integer pageSize) {
        PageDataResult pageDataResult = new PageDataResult();
        List<PlateDTO> plateList = backPlateMapper.getPlateList();

        PageHelper.startPage(pageNum, pageSize);

        if(plateList.size() != 0){
            PageInfo<PlateDTO> pageInfo = new PageInfo<>(plateList);
            pageDataResult.setList(plateList);
            pageDataResult.setTotals((int) pageInfo.getTotal());
        }

        return pageDataResult;
    }

    @Override
    public BBSPlate getPlateById(String id) {
        BBSPlate plate = backPlateMapper.getPlateById(id);
        return plate;
    }

    @Override
    public BBSArticle getArticleById(String id) {
        BBSArticle article = backArticleMapper.getArticleById(id);
        return article;
    }

    @Override
    public PageDataResult getArticleList(Integer pageNum, Integer pageSize) {
        PageDataResult pageDataResult = new PageDataResult();
        String userId = hostHolder.getUser().getId();
        List<ArticleDTO> articleList = backArticleMapper.getArticleList(userId);

        PageHelper.startPage(pageNum, pageSize);

        if(articleList.size() != 0){

            //遍历所属板块和自用户自定义类别
            for (ArticleDTO article : articleList){
                String plateId = article.getPlateId();
                String categoryIds = article.getCategoryId();
                if(AOSUtils.isNotEmpty(plateId)){
                    String plateName = backPlateMapper.getPlateById(plateId).getPlateName();
                    article.setPlateName(plateName);
                }
                if(AOSUtils.isNotEmpty(categoryIds)){
                    List<BBSCategory> categoryList = categoryMapper.getCategoryListByIds(categoryIds);
                    String categoryName = "[";
                    for (BBSCategory category : categoryList) {
                        categoryName += category.getCategoryName() + ",";
                    }
                    if (categoryName.length()>1){

                        categoryName = categoryName.trim().substring(0,categoryName.lastIndexOf(","));
                    }
                    categoryName += "]";
                    article.setCategoryName(categoryName);
                }
            }

            PageInfo<ArticleDTO> pageInfo = new PageInfo<>(articleList);
            pageDataResult.setList(articleList);
            pageDataResult.setTotals((int) pageInfo.getTotal());
        }

        return pageDataResult;
    }

    @Override
    public Map<String, Object> addArticle(BBSArticle article) {
        Map<String,Object> data = new HashMap();
        try {
            //默认字段
            article.setCreateDate(DateUtils.getCurrentDateToDate());
            article.setCreateBy(hostHolder.getUser().getUserName());
            article.setCreateName(hostHolder.getUser().getRealName());
            article.setUpdateDate(DateUtils.getCurrentDateToDate());
            article.setUpdateBy(hostHolder.getUser().getUserName());
            article.setUpdateName(hostHolder.getUser().getRealName());
            article.setDeleted(1);
            article.setId(CommunityUtil.generateUUID());
            article.setViewCount(0L);
            article.setArticleAttribute(1);
            article.setCommentCount(0L);
            article.setLikesCount(0L);
            article.setUserId(hostHolder.getUser().getId());

            if(article.getStatus() != null && article.getStatus() == 0){
                article.setBpmStatus(ArticleConstants.ARTICLE_WAIT_ISSUE);
            }else {
                article.setBpmStatus(ArticleConstants.ARTICLE_WAIT_AUDIT);
            }


            int result = backArticleMapper.insertArticle(article);
            if(result == 0){
                data.put("code",0);
                data.put("msg","新增失败！");
                logger.error("博文[新增]，结果=新增失败！");
                return data;
            }
            data.put("code",1);
            data.put("msg","新增成功！");
            logger.info("博文[新增]，结果=新增成功！");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("博文[新增]异常！", e);
            return data;
        }
        return data;
    }

    @Override
    public Map<String, Object> updateArticle(BBSArticle article) {
        Map<String,Object> data = new HashMap();
        try{
            article.setUpdateName(hostHolder.getUser().getRealName());
            article.setUpdateBy(hostHolder.getUser().getUserName());
            article.setUpdateDate(DateUtils.getCurrentDateToDate());
            if(article.getStatus() != null && article.getStatus() == 0){
                article.setBpmStatus(ArticleConstants.ARTICLE_WAIT_ISSUE);
            }else {
                article.setBpmStatus(ArticleConstants.ARTICLE_WAIT_AUDIT);
            }
            int result = backArticleMapper.updateArticle(article);
            if(result == 0){
                data.put("code",0);
                data.put("msg","更新失败！");
                logger.error("博文[更新]，结果=更新失败！");
                return data;
            }
            data.put("code",1);
            data.put("msg","更新成功！");
            logger.info("博文[更新]，结果=更新成功！");
        }catch (Exception e) {
            e.printStackTrace();
            logger.error("博文[更新]异常！", e);
            return data;
        }
        return data;
    }
}
